package com.hornsun.client.common.api;


import com.aliyuncs.exceptions.ClientException;
import com.google.common.base.Preconditions;
import com.hornsun.client.personalPage.service.HealthBeansService;
import com.hornsun.configInfo.ConfigInfo;
import com.hornsun.domain.constant.types.BoundType;
import com.hornsun.domain.constant.types.HealthBeansSource;
import com.hornsun.domain.constant.types.VerifyType;
import com.hornsun.domain.dbo.Member;
import com.hornsun.domain.dbo.Verify;
import com.hornsun.repository.MemberRepository;
import com.hornsun.repository.MemberWechatRepository;
import com.hornsun.repository.VerifyRepository;
import com.hornsun.repository.mapper.MemberWechatMapper;
import com.hornsun.util.StrUtil;
import com.hornsun.util.VerifyCodeUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

/**
 * Created by 编译中... on 2018/4/28.
 */
@RestController
@RequestMapping("/api/bound")
public class BoundAPI {

    @Resource
    private MemberWechatRepository memberWechatRepository;

    @Resource
    private MemberRepository memberRepository;

    @Resource
    private MemberWechatMapper memberWechatMapper;

    @Resource
    private ConfigInfo configInfo;

    @Resource
    private VerifyRepository verifyRepository;

    @Resource
    private HealthBeansService healthBeansService;


    @GetMapping("/checkBound")
    public ResponseEntity<?> checkBound(HttpServletRequest httpRequest){
        String openid = httpRequest.getAttribute("openid").toString();
        String memberGuid = memberWechatRepository.getMemberGuidByOpenid(openid);
        return new ResponseEntity<Object>(!(memberGuid == null || memberGuid.isEmpty()), HttpStatus.OK);
    }


    @PostMapping("/boundMember")
    public ResponseEntity<?> bound(HttpServletRequest httpRequest,@RequestParam("mobile")String mobile,@RequestParam("code")String code){
        String openid = httpRequest.getAttribute("openid").toString();
        if (mobile == null || mobile.isEmpty()||code==null||code.isEmpty()) {
            return new ResponseEntity<Object>("手机号或密码不能为空", HttpStatus.OK);
        }
        if (verifyRepository.hasExistAndNotOverdue(mobile,code,VerifyType.MOBILEBOUND.getType().byteValue())){
            List<Member> memberList = memberRepository.selectMemberByMobile(mobile);
            if(memberList.size()==1){
                if (memberWechatRepository.countByGuid(memberList.get(0).getMemberGuid())==1){
                    return new ResponseEntity<Object>(BoundType.BOUNDED.getType(),HttpStatus.OK);
                }else {
                    memberWechatMapper.boundMember(openid, memberList.get(0).getMemberGuid());
                    healthBeansService.gainHealthBeans(openid, configInfo.getFirstBound(), HealthBeansSource.FIRSTBOUNT.getName());
                    return new ResponseEntity<Object>(BoundType.EXIST.getType(), HttpStatus.OK);
                }
            }else {
                return new ResponseEntity<Object>(BoundType.UNEXIST.getType(),HttpStatus.OK);
            }
        }else {
            return new ResponseEntity<Object>("验证错误",HttpStatus.OK);
        }


    }

    @Transactional
    @PostMapping("/sendVerify")
    public ResponseEntity<?> sendVerify(@RequestParam("mobile")String mobile) throws ClientException {
        if (!StrUtil.isPhoneNumber(mobile)) {
            return new ResponseEntity<Object>("请输入正确的手机号码", HttpStatus.OK);
        }
        verifyRepository.deleteByMobileAndType(mobile, VerifyType.MOBILEBOUND.getType().byteValue());
        String code = StrUtil.random();
        String signName = configInfo.getSignName();
        String template = configInfo.getSmsTemplate();
        Verify verify = new Verify();
        verify.setMobile(mobile);
        verify.setCode(code);
        verify.setType(VerifyType.MOBILEBOUND.getType().byteValue());
        verifyRepository.insert(verify);
        VerifyCodeUtil.sendSms(mobile,code,signName,template);
        return new ResponseEntity<Object>(code,HttpStatus.OK);
    }


    @Transactional
    @PostMapping("/register")
    public ResponseEntity<?> register(HttpServletRequest httpRequest,Member member){
        String openid = httpRequest.getAttribute("openid").toString();
        Preconditions.checkNotNull(member);
        Preconditions.checkNotNull(member.getMobile());
        Preconditions.checkNotNull(member.getGender());
        Preconditions.checkNotNull(member.getName());
        String guid = UUID.randomUUID().toString();
        member.setMemberGuid(guid);
        memberRepository.insertMember(member);
        memberWechatMapper.boundMember(openid, guid);
        healthBeansService.gainHealthBeans(openid, configInfo.getFirstBound(), HealthBeansSource.FIRSTBOUNT.getName());
        return new ResponseEntity<Object>(HttpStatus.OK);
    }
}